#include "PointLabIO/Factory.h"
#include "PointLabIO/FileInfo.h"

namespace PointLabIO
{
	Factory::Factory()
	{
	}

	Factory::~Factory()
	{
	}

	bool Factory::IORegister(PointLabIO::BaseIO* bi)
	{
		if (bi->importSupported() || bi->exportSupported())
		{
			mIoClosses.insert(bi);
			return true;
		}
		else
		{
			return false;
		}
	}

	PointLabIO::POINTLAB_FILE_ERROR Factory::LoadFromFile(const std::string fileName, PointLabCore::Entity*& entity, PointLabIO::Options& options)
	{
		auto it = mIoClosses.begin();
		auto itEnd = mIoClosses.end();

		while (it != itEnd)
		{
			std::string fileSuffix = FileInfo(fileName).suffix();

			if ((*it)->importSupported() && (*it)->canLoadExtension(fileSuffix))
			{
				return (*it)->loadFile(fileName, entity, options);
			}
			++it;
		}

		return POINTLAB_FILE_ERROR::POINTLAB_FILE_NO_LOAD;
	}

	PointLabIO::POINTLAB_FILE_ERROR Factory::SaveToFile(const std::string fileName, PointLabCore::Entity* entity, PointLabIO::Options& options)
	{
		auto it = mIoClosses.begin();
		auto itEnd = mIoClosses.end();

		while (it != itEnd)
		{
			if ((*it)->canSave(entity->classID()))
			{
				return (*it)->saveToFile(fileName, entity, options);
			}
			++it;
		}
		return POINTLAB_FILE_ERROR::POINTLAB_FILE_NO_SAVE;
	}

	const std::vector<std::string> Factory::filters() const
	{
		std::vector<std::string> filterList;

		auto it = mIoClosses.begin();
		auto itEnd = mIoClosses.end();

		while (it != itEnd)
		{
			if ((*it)->importSupported())
			{
				filterList.push_back((*it)->fileFilters());
			}
			++it;
		}

		return filterList;
	}

	PointLabIO::Factory& Handler()
	{
		static PointLabIO::Factory factoryInstance;
		return factoryInstance;
	}
}